package com.wss.lsl.dubbo.portal.web;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.wss.lsl.dubbo.demo.tools.util.DateUtil;
import com.wss.lsl.server.util.Permission;
import com.wss.lsl.server.util.dto.LoginUser;

/**
 * 登录 controller
 * 
 * @author sean
 *
 */
@Controller
@RequestMapping(value = "/login")
public class LoginController {
	private static final Logger LOG = LoggerFactory.getLogger(LoginController.class);
	
	/**
	 * 执行登录操作
	 * 
	 * @param username
	 * @param session
	 * @return
	 */
	@Permission(needLogin = false)
	@RequestMapping(value = "/do_login")
	public String login(String username, HttpSession session) {
		
		LOG.info("登录参数：username={}", username);
		
		Date loginTime = new Date();

		LoginUser loginUser = new LoginUser();
		loginUser.setUsername(username);
		loginUser.setLoginTime(DateUtil.date2String(loginTime, DateUtil.DATE_FORMAT_YYYYMMDDHHMISS));
		
		session.setAttribute("loginUser", loginUser);
		
		return "redirect:/main/index.do";
	}
	
	/**
	 * 进入登录页面
	 * 
	 * @return
	 */
	@Permission(needLogin = false)
	@RequestMapping(value="/login")
	public String login(){
		
		LOG.info("进入了登录页面");
		return "login";
	}
	
	/**
	 * 登出
	 * 
	 * @param session
	 * @return
	 */
	@Permission(needLogin = false)
	@RequestMapping(value="/do_logout")
	public String logout(HttpServletRequest request) {

		try {
			HttpSession session = request.getSession();
			LoginUser loginUser = (LoginUser)session.getAttribute("loginUser");
			session.invalidate();
			if(null != loginUser) {
				String currentUserValue = loginUser.getUsername() + "_" + loginUser.getLoginTime();
				session = request.getSession(true);
				session.setAttribute("logoutUser", currentUserValue);
			}
		} catch (Exception e) {
			LOG.info("登出发生异常", e);
		}

		return "redirect:/login/login.do";
	}
}
